package com.dkha.server.controllers;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dkha.common.fileupload.MinioUtil;
import com.dkha.common.http.HttpUtil;
import com.dkha.common.modules.vo.face.ApiSearchFaceRectVO;
import com.dkha.common.modules.vo.face.FaceResEntity;
import com.dkha.common.modules.vo.CompareFaceList;
import com.dkha.common.modules.vo.search.SearchPortraitVo;
import com.dkha.common.modules.vo.search.SearchRequestVo;
import com.dkha.common.modules.vo.search.SearchResultVo;
import com.dkha.common.page.PageParam;
import com.dkha.common.result.CommonResult;
import com.dkha.common.modules.vo.ReturnVO;
import com.dkha.common.util.JsonUtil;
import com.dkha.common.util.UtilValidate;
import com.dkha.server.mappers.PortraitMapper;
import com.dkha.server.mappers.FaceInformationMapper;
import com.dkha.server.modules.entities.FaceInformation;
import com.dkha.server.modules.entities.Portrait;
import com.dkha.server.services.IPortraitService;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.*;
import java.util.function.Function;


@RestController
@RequestMapping("faces")
@Slf4j
@Component
public class FaceController extends CommonResult {
    @Resource
    private MinioUtil minioUtil;
    @Value("${api.server.prefix}")
    private String apiServerPrefix;
    @Autowired
    private HttpUtil httpUtil;

    @Autowired
    private IPortraitService iPortraitService;
    @Autowired
    private PortraitMapper portraitMapper;
    @Autowired
    private  FaceInformationMapper faceInformationMapper;
    @Autowired
    private Gson gson;

    private  int count ;

    private List<FaceResEntity> facelist = new ArrayList<>();

    private List<CompareFaceList> compareFaceLists = new ArrayList<>();

    private List<FaceInformation> faceInformations =new ArrayList<>();
    public  FaceController(){
        //FaceResEntity  resEntity = new FaceResEntity();
        //resEntity.setTime("jhx");
        // resEntity.setRphoto("http://192.168.60.52:9000/school/face/jhx.jpg");
        //faceRes.put("eYJST7eY2mbnjGZvywPfxg==",resEntity);
    }

    /*@RequestMapping("callback")
    public String callback(HttpServletRequest request) throws IOException {
        try {
        String streamText = RequestUtil.getStreamText(request);
        System.out.println(streamText);
        JSONObject object = JSONObject.parseObject(streamText);
        String str = object.get("photo").toString();
        String xsd =  object.get("confidence").toString();
        byte[] _byte =  new BASE64Decoder().decodeBuffer(str);
        InputStream inputStream = new ByteArrayInputStream(_byte);

        String  object1 =   "http://192.168.1.133:9000/middleware/"+minioUtil.uploadImage(inputStream,"").getString("path");
        System.out.println(object1);
            if( faceRes.get(object.getString("ImageID"))!=null){
                FaceResEntity resEntity =  faceRes.get(object.getString("ImageID"));
                resEntity.setCphoto(object1);
                //resEntity.setXsd(xsd.substring(0,5));
                list.add(resEntity);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "ok";
    }

    @GetMapping("list")
    public List<FaceResEntity> getList(){
        list.clear();
        //System.out.println("返回list测试:" + list);
        //String testUrl = apiServerPrefix + ApiUrlEnum.FACE_SEARCH.getUrl();
        String testUrl = "http://192.168.1.196:5000/cutimage";
        System.out.println("testurl:"+ testUrl);
        ReturnVO returnVO = (ReturnVO) httpUtil.post(testUrl, null, ReturnVO.class);
        List<FaceResEntity> resEntity = JsonUtil.string2Obj(JsonUtil.obj2String(returnVO.getData()), new TypeReference<List<FaceResEntity>>() {});
        //FaceResEntity  resEntity = new FaceResEntity();
        //resEntity.setName("ceshi");
        //resEntity.setCphoto("http://192.168.1.133:9000/middleware/103/1028345463.jpg");
        for(FaceResEntity res :resEntity) {
            System.out.println("resEntity cphoto:"+ res.getCphoto());
            list.add(res);
        }
        System.out.println("返回list测试:" + list);
        return list;
        //return (List<FaceResEntity>) successResult(list);
    }
*/
    @GetMapping( "returnList")
    public List<FaceResEntity> returnList(){
        System.out.println("开始returnlist");
        System.out.println(facelist.size());
        return facelist;
    }
    @PostMapping("/test123")
    public void test(@RequestBody List<FaceInformation> testcompareFacelist){
            faceInformations.clear();
        for (FaceInformation faceInformation :testcompareFacelist){
            QueryWrapper<Portrait> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("id_portrait",faceInformation.getName());
            Portrait rphoto = iPortraitService.getBaseMapper().selectOne(queryWrapper);

            faceInformation.setRphoto(rphoto.getUrl());
            faceInformation.setName(rphoto.getName());
            faceInformations.add(faceInformation);
            faceInformationMapper.insert(faceInformation);
        }

    }

    //从算法端获取图片列表接口
    @PostMapping("/getList")
    public void getList(
            @RequestBody List<FaceResEntity> resEntities) {
        System.out.println("getlist被请求");
        facelist.clear();
        //System.out.println(resEntities);
        for (FaceResEntity res :resEntities){
            count++;
            facelist.add(res);
        }
        WebSocketContral webSocketContral =new WebSocketContral();
        webSocketContral.sendMessage(gson.toJson(facelist));
        System.out.println("发送信息结束");
    }

    public  void sendWebsocket1(List<FaceResEntity> onfacelist){
        facelist.clear();
        facelist = onfacelist;
        //System.out.println(facelist);
        WebSocketContral webSocketContral =new WebSocketContral();
        webSocketContral.sendMessage(gson.toJson(facelist));
        //System.out.println("发送信息结束");
    }

    public  void sendWebsocket2(List<FaceInformation> onfaceInformations){
        faceInformations.clear();
        long a = System.currentTimeMillis();
//        compareFaceLists = oncompareFacelist;
        for (FaceInformation faceInformation :onfaceInformations){
//            if(UtilValidate.isNotEmpty(com.getName())){
                //根据人脸名称,实际是id——portrait去人像库中寻找rphoto
                QueryWrapper<Portrait> queryWrapper=new QueryWrapper<>();
                queryWrapper.eq("id_portrait",faceInformation.getName());
                Portrait rphoto = iPortraitService.getBaseMapper().selectOne(queryWrapper);
//                System.out.println("rphoto"+rphoto);
                //判断数据库中查找的数据是否为空
                faceInformation.setRphoto(rphoto.getUrl());
                faceInformation.setName(rphoto.getName());
//            }
                //  将预警数据加入列表中
                faceInformations.add(faceInformation);
                //将预警数据存入数据库中
                faceInformationMapper.insert(faceInformation);
                //faceInformationMapper.insert(faceInformation);
        }
        long b = System.currentTimeMillis();
        System.out.println("查表数据时间"+(b-a)+"ms");
//        System.out.println(compareFaceLists);
        //websocket发送预警数据
        WebSocketContral webSocketContral =new WebSocketContral();
        webSocketContral.sendMessage(gson.toJson(faceInformations));
        long c =System.currentTimeMillis();
        SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MM-dd aHH:mm:ss:SSS");
        System.out.println("websocket发送完成时间点"+ dateFormatGmt.format(new Date())+ "，共耗时"+(c-b)+"ms");
    }

    @PostMapping("/compareList")
    public void compareList(
            @RequestBody List<CompareFaceList> faceLists ){
        compareFaceLists.clear();
        System.out.println("facelist"+faceLists);
        for (CompareFaceList com :faceLists){
            if(UtilValidate.isNotEmpty(com.getName())){
                //人脸数量
                QueryWrapper<Portrait> queryWrapper=new QueryWrapper<>();
                queryWrapper.select("url").eq("name",com.getName());
               Portrait rphoto = portraitMapper.selectOne(queryWrapper);
                System.out.println("rphoto:"+rphoto);
//                com.setName(rphoto.getUrl());
            }
//            compareFaceLists.add(com);
        }
        System.out.println(compareFaceLists);
    }

    public List<FaceResEntity> getFacelist() {
        return this.facelist;
    }
    @GetMapping("test0509")
    public void getUrl(@RequestParam("url") String url) {
        System.out.println(apiServerPrefix);
        System.out.println("获取url"+url);
    }

   /*    @GetMapping("one")
    public List<String getOne(){
        if(list.isEmpty()){
            return  "";
        }
        return list.get(list.size()-1).getCphoto();
    }*/


}
